package com.jakewharton.rxbinding2.widget;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.ohos.MainThreadDisposable;
import ohos.agp.components.Component;
import ohos.agp.components.ListContainer;

import static com.jakewharton.rxbinding2.internal.Preconditions.checkMainThread;

final class ListContainerScrollEventObservable extends Observable<ListContainerScrollEvent> {
  private final ListContainer view;

  ListContainerScrollEventObservable(ListContainer view) {
    this.view = view;
  }

  @Override protected void subscribeActual(Observer<? super ListContainerScrollEvent> observer) {
    if (!checkMainThread(observer)) {
      return;
    }
    Listener listener = new Listener(view, observer);
    observer.onSubscribe(listener);
    view.setScrolledListener(listener);
  }

  static final class Listener extends MainThreadDisposable implements Component.ScrolledListener {
    private final ListContainer view;
    private final Observer<? super ListContainerScrollEvent> observer;

    Listener(ListContainer view, Observer<? super ListContainerScrollEvent> observer) {
      this.view = view;
      this.observer = observer;
    }

    @Override protected void onDispose() {
      view.setScrolledListener(null);
    }

    @Override
    public void onContentScrolled(Component component, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
      if (!isDisposed()) {
        ListContainerScrollEvent event =
                ListContainerScrollEvent.create(view, scrollX, scrollY, oldScrollX, oldScrollY);
        observer.onNext(event);
      }
    }
  }
}
